import java.util.Scanner
import kotlin.system.exitProcess

class ContactExt private constructor(){
    companion object {
        /**
         * by lazy 懒加载
         * 定义时不加载，使用时才加载
         * 只会被加载一次
         */
        val instance: ContactExt by lazy {
            ContactExt()
        }
    }

    //容器保存所有联系人

    private val sectionList:ArrayList<Section> = ArrayList()
    //保存每个小组的组名
    private val titles: ArrayList<Char> = arrayListOf()

    //添加好友
    fun add(name:String){
        addFriend(Person().apply { this.name = name })
    }

    private fun addFriend(person: Person) {
        //判断有没有自己的小组
        if (titles.contains(person.title)){
            //找到section
            for (section in sectionList){
                if (section.title == person.title){
                    section.add(person)
                    break
                }
            }
        }else{
           val section = Section(person.title, arrayListOf(person))
            sectionList.add(section)
            titles.add(person.title)
        }

        //对section排序
        sectionList.sortBy {
            it.title
        }
    }

    //删除好友
    fun delete(name: String){
        val person = Person().apply { this.name = name }
        //判断有没有这一组
        if (titles.contains(person.title)){
            //判断小组好友中有没有这个人
            for (section in sectionList){
                //招section
                if (section.title == person.title){
                    section.delete(person.name)
                    if (section.friendList.isEmpty()){
                        sectionList.remove(section)
                        titles.remove(person.title)
                    }
                    break
                }
            }
        }
    }

    //显示好友列表
    fun show(){
        sectionList.forEach { it.show() }
    }
}

fun main() {
    ContactExt.instance.add("彭孝东")
    ContactExt.instance.add("旁小动")
    ContactExt.instance.add("彭德怀")
    ContactExt.instance.add("毛泽东")
    ContactExt.instance.add("毛爱英")
    ContactExt.instance.add("李娜")

    val scanner = Scanner(System.`in`)
    while (true){
        OperationInterface.instance.showMenu()
        OperationInterface.instance.choose{
            when(it){
                OperationType.ADD ->{
                    print("请输入好友姓名:")
                    ContactExt.instance.add(scanner.nextLine())
                }
                OperationType.REMOVE ->{
                    print("请输入好友姓名:")
                    ContactExt.instance.delete(scanner.nextLine())
                }
                OperationType.SHOW ->{
                    ContactExt.instance.show()
                }
                OperationType.EXIT ->{
                    exitProcess(1)
                }
            }
        }

    }
}